package com.bo.day20241121;

/**
 * 图转换
 *
 * @Author: gpb
 * @Date: 2024/11/22 14:37
 * @Description:
 */
public class GraphGenerator {

    /**
     * 邻接矩阵转图
     * [5,0,7] // 表示 权重是5, 从0到7
     * [5,1,9] // 表示 权重是5, 从1到9
     *
     * @param matrix
     * @return
     */
    public static Graph createGraph (Integer[][] matrix) {
        Graph graph = new Graph();
        for (int i = 0; i < matrix.length; i++) {
            // 权重
            int weight = matrix[i][0];
            // from
            int from = matrix[i][1];
            // to
            int to = matrix[i][2];
            // 如果节点不存在，就创建一个节点
            if (!graph.nodes.containsKey(from)) {
                graph.nodes.put(from, new Node(from));
            }
            if (!graph.nodes.containsKey(to)) {
                graph.nodes.put(to, new Node(to));
            }
            Node fromNode = graph.nodes.get(from);
            Node toNode = graph.nodes.get(to);
            // 出度+1
            fromNode.out++;
            // 入度+1
            toNode.in++;
            // 创建边
            Edge edge = new Edge(weight, fromNode, toNode);
            // 添加到图中
            fromNode.nexts.add(toNode);
            fromNode.edges.add(edge);
            graph.edges.add(edge);
        }
        return graph;
    }
}
